package com.agritech.smartfarming.ui;

import com.agritech.smartfarming.factory.*;
import com.agritech.smartfarming.model.*;
import com.agritech.smartfarming.observer.EnvironmentMonitor;
import com.agritech.smartfarming.service.UserService;
import com.agritech.smartfarming.strategy.*;
import com.agritech.smartfarming.chainofresponsibility.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 主界面
 */
public class MainFrame extends JFrame {
    private final UserService userService;
    private JTabbedPane tabbedPane;
    private JPanel machinePanel;
    private JPanel environmentPanel;
    private JPanel userPanel;
    
    // 农机设备相关
    private List<AgriculturalMachine> machines;
    private EnvironmentMonitor environmentMonitor;
    private JComboBox<String> machineComboBox;
    private JTextArea machineInfoArea;
    private JButton startButton;
    private JButton stopButton;
    private JButton taskButton;
    
    // 环境数据相关
    private JTextField soilMoistureField;
    private JTextField soilPHField;
    private JTextField soilNutrientField;
    private JTextField temperatureField;
    private JTextField humidityField;
    private JTextField windSpeedField;
    private JTextField windDirectionField;
    private JTextField cropHeightField;
    private JTextField cropStatusField;
    
    // 用户管理相关
    private JComboBox<String> userComboBox;
    private JTextArea userInfoArea;
    private JButton addUserButton;
    private JButton deleteUserButton;
    private JButton editUserButton;
    
    public MainFrame() {
        userService = UserService.getInstance();
        initComponents();
        initMachines();
    }
    
    private void initComponents() {
        setTitle("智能无人驾驶农机系统 - " + userService.getCurrentUser().getUsername() + " (" + userService.getCurrentUser().getRole() + ")");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建选项卡面板
        tabbedPane = new JTabbedPane();
        
        // 创建农机管理面板
        machinePanel = createMachinePanel();
        tabbedPane.addTab("农机管理", machinePanel);
        
        // 创建环境监测面板
        environmentPanel = createEnvironmentPanel();
        tabbedPane.addTab("环境监测", environmentPanel);
        
        // 创建用户管理面板（仅管理员可见）
        if (userService.getCurrentUser().getRole() == UserRole.ADMIN) {
            userPanel = createUserPanel();
            tabbedPane.addTab("用户管理", userPanel);
        }
        
        // 创建菜单栏
        JMenuBar menuBar = createMenuBar();
        setJMenuBar(menuBar);
        
        // 添加选项卡面板到窗口
        getContentPane().add(tabbedPane);
    }
    
    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        
        // 系统菜单
        JMenu systemMenu = new JMenu("系统");
        JMenuItem logoutItem = new JMenuItem("退出登录");
        JMenuItem exitItem = new JMenuItem("退出系统");
        
        systemMenu.add(logoutItem);
        systemMenu.addSeparator();
        systemMenu.add(exitItem);
        
        // 帮助菜单
        JMenu helpMenu = new JMenu("帮助");
        JMenuItem aboutItem = new JMenuItem("关于");
        
        helpMenu.add(aboutItem);
        
        // 添加菜单到菜单栏
        menuBar.add(systemMenu);
        menuBar.add(helpMenu);
        
        // 添加菜单项事件
        logoutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                userService.logout();
                LoginFrame loginFrame = new LoginFrame();
                loginFrame.setVisible(true);
                dispose();
            }
        });
        
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(MainFrame.this,
                        "智能无人驾驶农机系统\n\n" +
                        "基于Java技术的智能无人驾驶农机系统，整合物联网、人工智能和自动化技术，\n" +
                        "实现农田作业的全面智能化。系统支持无人驾驶拖拉机、智能播种机、自动收割机等\n" +
                        "多种农机设备协同作业，并能根据环境信息实时调整作业策略。",
                        "关于系统",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        return menuBar;
    }
    
    private JPanel createMachinePanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建农机选择和信息展示区域
        JPanel northPanel = new JPanel(new BorderLayout());
        
        // 农机选择下拉框
        JPanel selectPanel = new JPanel();
        selectPanel.add(new JLabel("选择农机:"));
        machineComboBox = new JComboBox<>();
        machineComboBox.setPreferredSize(new Dimension(200, 25));
        selectPanel.add(machineComboBox);
        
        northPanel.add(selectPanel, BorderLayout.NORTH);
        
        // 农机信息显示区域
        machineInfoArea = new JTextArea(10, 40);
        machineInfoArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(machineInfoArea);
        northPanel.add(scrollPane, BorderLayout.CENTER);
        
        panel.add(northPanel, BorderLayout.NORTH);
        
        // 创建控制按钮区域
        JPanel controlPanel = new JPanel();
        controlPanel.setBorder(BorderFactory.createTitledBorder("农机控制"));
        
        startButton = new JButton("启动");
        stopButton = new JButton("停止");
        taskButton = new JButton("执行任务");
        JButton pathButton = new JButton("路径规划");
        JButton unloadButton = new JButton("卸粮");
        
        // 根据用户角色设置按钮可用性
        boolean canControl = userService.getCurrentUser().getRole() == UserRole.ADMIN || 
                            userService.getCurrentUser().getRole() == UserRole.OPERATOR;
        startButton.setEnabled(canControl);
        stopButton.setEnabled(canControl);
        taskButton.setEnabled(canControl);
        pathButton.setEnabled(canControl);
        unloadButton.setEnabled(canControl);
        
        controlPanel.add(startButton);
        controlPanel.add(stopButton);
        controlPanel.add(taskButton);
        controlPanel.add(pathButton);
        controlPanel.add(unloadButton);
        
        panel.add(controlPanel, BorderLayout.CENTER);
        
        // 添加事件监听器
        machineComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateMachineInfo();
                
                // 只有当选择的是收割机时，卸粮按钮才可用
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    boolean isHarvester = machines.get(index) instanceof Harvester;
                    unloadButton.setEnabled(canControl && isHarvester);
                }
            }
        });
        
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    machines.get(index).start();
                    updateMachineInfo();
                }
            }
        });
        
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    machines.get(index).stop();
                    updateMachineInfo();
                }
            }
        });
        
        taskButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    machines.get(index).performTask();
                    updateMachineInfo();
                }
            }
        });
        
        pathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    JPanel strategyPanel = new JPanel(new GridLayout(0, 1));
                    ButtonGroup group = new ButtonGroup();
                    
                    JRadioButton standardBtn = new JRadioButton("标准路径策略");
                    JRadioButton terrainBtn = new JRadioButton("地形感知策略");
                    JRadioButton energyBtn = new JRadioButton("能源效率策略");
                    
                    group.add(standardBtn);
                    group.add(terrainBtn);
                    group.add(energyBtn);
                    
                    strategyPanel.add(standardBtn);
                    strategyPanel.add(terrainBtn);
                    strategyPanel.add(energyBtn);
                    
                    standardBtn.setSelected(true);
                    
                    int result = JOptionPane.showConfirmDialog(
                            MainFrame.this,
                            strategyPanel,
                            "选择路径规划策略",
                            JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    
                    if (result == JOptionPane.OK_OPTION) {
                        AgriculturalMachine machine = machines.get(index);
                        PathPlanningStrategy strategy = null;
                        
                        if (standardBtn.isSelected()) {
                            strategy = new StandardPathStrategy();
                        } else if (terrainBtn.isSelected()) {
                            strategy = new TerrainAwarePathStrategy();
                        } else if (energyBtn.isSelected()) {
                            strategy = new EnergyEfficientPathStrategy();
                        }
                        
                        if (strategy != null) {
                            machine.setPathPlanningStrategy(strategy);
                            Position startPos = new Position(39.9042, 116.4074, 50.0);
                            Position endPos = new Position(39.9142, 116.4174, 55.0);
                            machine.planPath(startPos, endPos);
                        }
                    }
                }
            }
        });
        
        // 添加卸粮按钮事件
        unloadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = machineComboBox.getSelectedIndex();
                if (index >= 0 && index < machines.size()) {
                    AgriculturalMachine machine = machines.get(index);
                    if (machine instanceof Harvester) {
                        Harvester harvester = (Harvester) machine;
                        harvester.unloadGrain();
                        updateMachineInfo();
                        JOptionPane.showMessageDialog(MainFrame.this,
                                "卸粮操作已完成",
                                "操作成功",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(MainFrame.this,
                                "只有收割机才能执行卸粮操作",
                                "操作失败",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        
        return panel;
    }
    
    private JPanel createEnvironmentPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建环境数据输入区域
        JPanel inputPanel = new JPanel(new GridLayout(0, 2, 10, 5));
        inputPanel.setBorder(BorderFactory.createTitledBorder("环境数据输入"));
        
        // 土壤数据
        inputPanel.add(new JLabel("土壤湿度 (%):"));
        soilMoistureField = new JTextField("75.0");
        inputPanel.add(soilMoistureField);
        
        inputPanel.add(new JLabel("土壤pH值:"));
        soilPHField = new JTextField("6.5");
        inputPanel.add(soilPHField);
        
        inputPanel.add(new JLabel("土壤养分指数:"));
        soilNutrientField = new JTextField("80.0");
        inputPanel.add(soilNutrientField);
        
        // 气象数据
        inputPanel.add(new JLabel("温度 (℃):"));
        temperatureField = new JTextField("25.0");
        inputPanel.add(temperatureField);
        
        inputPanel.add(new JLabel("空气湿度 (%):"));
        humidityField = new JTextField("60.0");
        inputPanel.add(humidityField);
        
        inputPanel.add(new JLabel("风速 (m/s):"));
        windSpeedField = new JTextField("5.0");
        inputPanel.add(windSpeedField);
        
        inputPanel.add(new JLabel("风向:"));
        windDirectionField = new JTextField("东北风");
        inputPanel.add(windDirectionField);
        
        // 作物数据
        inputPanel.add(new JLabel("作物高度 (cm):"));
        cropHeightField = new JTextField("60.0");
        inputPanel.add(cropHeightField);
        
        inputPanel.add(new JLabel("作物状态:"));
        cropStatusField = new JTextField("生长良好");
        inputPanel.add(cropStatusField);
        
        panel.add(inputPanel, BorderLayout.NORTH);
        
        // 创建按钮区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("更新环境数据");
        
        // 根据用户角色设置按钮可用性
        boolean canUpdate = userService.getCurrentUser().getRole() != UserRole.GUEST;
        updateButton.setEnabled(canUpdate);
        
        buttonPanel.add(updateButton);
        panel.add(buttonPanel, BorderLayout.CENTER);
        
        // 添加事件监听器
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double soilMoisture = Double.parseDouble(soilMoistureField.getText());
                    double soilPH = Double.parseDouble(soilPHField.getText());
                    double soilNutrient = Double.parseDouble(soilNutrientField.getText());
                    double temperature = Double.parseDouble(temperatureField.getText());
                    double humidity = Double.parseDouble(humidityField.getText());
                    double windSpeed = Double.parseDouble(windSpeedField.getText());
                    String windDirection = windDirectionField.getText();
                    double cropHeight = Double.parseDouble(cropHeightField.getText());
                    String cropStatus = cropStatusField.getText();
                    
                    EnvironmentData environmentData = new EnvironmentData(
                        soilMoisture,
                        soilPH,
                        soilNutrient,
                        temperature,
                        humidity,
                        windSpeed,
                        windDirection,
                        cropHeight,
                        cropStatus,
                        new Position(39.9043, 116.4075, 50.0)
                    );
                    
                    environmentMonitor.updateEnvironmentData(environmentData);
                    JOptionPane.showMessageDialog(MainFrame.this,
                            "环境数据已更新，并通知所有农机设备",
                            "更新成功",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(MainFrame.this,
                            "请输入有效的数值",
                            "输入错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        return panel;
    }
    
    private JPanel createUserPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建用户选择和信息展示区域
        JPanel northPanel = new JPanel(new BorderLayout());
        
        // 用户选择下拉框
        JPanel selectPanel = new JPanel();
        selectPanel.add(new JLabel("选择用户:"));
        userComboBox = new JComboBox<>();
        userComboBox.setPreferredSize(new Dimension(200, 25));
        selectPanel.add(userComboBox);
        
        northPanel.add(selectPanel, BorderLayout.NORTH);
        
        // 用户信息显示区域
        userInfoArea = new JTextArea(10, 40);
        userInfoArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(userInfoArea);
        northPanel.add(scrollPane, BorderLayout.CENTER);
        
        panel.add(northPanel, BorderLayout.NORTH);
        
        // 创建控制按钮区域
        JPanel controlPanel = new JPanel();
        controlPanel.setBorder(BorderFactory.createTitledBorder("用户管理"));
        
        addUserButton = new JButton("添加用户");
        deleteUserButton = new JButton("删除用户");
        editUserButton = new JButton("编辑用户");
        
        controlPanel.add(addUserButton);
        controlPanel.add(deleteUserButton);
        controlPanel.add(editUserButton);
        
        panel.add(controlPanel, BorderLayout.CENTER);
        
        // 添加事件监听器
        userComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateUserInfo();
            }
        });
        
        // 添加用户按钮事件
        addUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                UserDialog dialog = new UserDialog(MainFrame.this, "添加新用户", null);
                dialog.setVisible(true);
                
                if (dialog.isConfirmed()) {
                    User newUser = dialog.getUser();
                    if (userService.addUser(newUser)) {
                        updateUserList();
                    }
                }
            }
        });
        
        // 删除用户按钮事件
        deleteUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = userComboBox.getSelectedIndex();
                if (index >= 0) {
                    List<User> users = userService.getAllUsers();
                    if (index < users.size()) {
                        User user = users.get(index);
                        
                        int confirm = JOptionPane.showConfirmDialog(
                                MainFrame.this,
                                "确定要删除用户 " + user.getUsername() + " 吗？",
                                "确认删除",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.WARNING_MESSAGE);
                        
                        if (confirm == JOptionPane.YES_OPTION) {
                            if (userService.deleteUser(user.getUserId())) {
                                updateUserList();
                            }
                        }
                    }
                }
            }
        });
        
        // 编辑用户按钮事件
        editUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = userComboBox.getSelectedIndex();
                if (index >= 0) {
                    List<User> users = userService.getAllUsers();
                    if (index < users.size()) {
                        User user = users.get(index);
                        
                        UserDialog dialog = new UserDialog(MainFrame.this, "编辑用户", user);
                        dialog.setVisible(true);
                        
                        if (dialog.isConfirmed()) {
                            User updatedUser = dialog.getUser();
                            if (userService.updateUser(updatedUser)) {
                                updateUserList();
                            }
                        }
                    }
                }
            }
        });
        
        // 初始化用户列表
        updateUserList();
        
        return panel;
    }
    
    private void initMachines() {
        // 创建环境监测器
        environmentMonitor = new EnvironmentMonitor();
        
        // 创建农机设备工厂
        AgriculturalMachineFactory tractorFactory = new TractorFactory();
        AgriculturalMachineFactory seederFactory = new SeederFactory();
        AgriculturalMachineFactory harvesterFactory = new HarvesterFactory();
        
        // 创建农机设备
        machines = new ArrayList<>();
        AgriculturalMachine tractor = tractorFactory.createMachine("T001", "智能拖拉机001");
        AgriculturalMachine seeder = seederFactory.createMachine("S001", "智能播种机001");
        AgriculturalMachine harvester = harvesterFactory.createMachine("H001", "智能收割机001");
        
        machines.add(tractor);
        machines.add(seeder);
        machines.add(harvester);
        
        // 注册农机设备为环境监测器的观察者
        environmentMonitor.registerObserver(tractor);
        environmentMonitor.registerObserver(seeder);
        environmentMonitor.registerObserver(harvester);
        
        // 设置农机位置
        tractor.setPosition(new Position(39.9042, 116.4074, 50.0));
        seeder.setPosition(new Position(39.9043, 116.4075, 50.0));
        harvester.setPosition(new Position(39.9044, 116.4076, 50.0));
        
        // 更新农机下拉框
        for (AgriculturalMachine machine : machines) {
            machineComboBox.addItem(machine.getName() + " (" + machine.getType() + ")");
        }
        
        // 初始化显示第一个农机的信息
        if (!machines.isEmpty()) {
            machineInfoArea.setText(machines.get(0).getStatusInfo());
        }
    }
    
    private void updateMachineInfo() {
        int index = machineComboBox.getSelectedIndex();
        if (index >= 0 && index < machines.size()) {
            AgriculturalMachine machine = machines.get(index);
            machineInfoArea.setText(machine.getStatusInfo());
            
            // 如果是特定类型的农机，显示额外信息
            if (machine instanceof Tractor) {
                machineInfoArea.append("\n\n" + ((Tractor) machine).getTractorInfo());
            } else if (machine instanceof Seeder) {
                machineInfoArea.append("\n\n" + ((Seeder) machine).getSeederInfo());
            } else if (machine instanceof Harvester) {
                machineInfoArea.append("\n\n" + ((Harvester) machine).getHarvesterInfo());
            }
        }
    }
    
    private void updateUserList() {
        if (userComboBox != null) {
            userComboBox.removeAllItems();
            List<User> users = userService.getAllUsers();
            for (User user : users) {
                userComboBox.addItem(user.getUsername() + " (" + user.getRole() + ")");
            }
            
            // 初始化显示第一个用户的信息
            if (!users.isEmpty()) {
                userInfoArea.setText(users.get(0).getUserInfo());
            }
        }
    }
    
    private void updateUserInfo() {
        int index = userComboBox.getSelectedIndex();
        if (index >= 0) {
            List<User> users = userService.getAllUsers();
            if (index < users.size()) {
                User user = users.get(index);
                userInfoArea.setText(user.getUserInfo());
            }
        }
    }
} 